package com.ioftv.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.ioftv.dto.LabelerDailyOutputExcelDTO;
import com.ioftv.entity.LabelerDailyOutput;
import com.ioftv.service.LabelerDailyOutputService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 标注员每日产值记录Excel导入监听器
 */
@Slf4j
public class LabelerDailyOutputImportListener implements ReadListener<LabelerDailyOutputExcelDTO> {

    private LabelerDailyOutputService labelerDailyOutputService;
    private List<LabelerDailyOutputExcelDTO> cachedDataList = new ArrayList<>();
    private static final int BATCH_COUNT = 100;
    
    private Long userId; // 用户ID，用于数据隔离

    public LabelerDailyOutputImportListener(LabelerDailyOutputService labelerDailyOutputService) {
        this.labelerDailyOutputService = labelerDailyOutputService;
    }
    
    /**
     * 设置用户ID
     * @param userId 用户ID
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    @Override
    public void invoke(LabelerDailyOutputExcelDTO data, AnalysisContext context) {
        log.debug("解析到一条数据: {}", data);
        cachedDataList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        for (LabelerDailyOutputExcelDTO excelDTO : cachedDataList) {
            LabelerDailyOutput record = new LabelerDailyOutput();
            record.setLabelerId(excelDTO.getLabelerId());
            record.setLabelerName(excelDTO.getLabelerName());
            record.setRecordDate(excelDTO.getRecordDate());
            record.setTargetBoxCount(excelDTO.getTargetBoxCount());
            record.setActualBoxCount(excelDTO.getActualBoxCount());
            record.setUncompletedReason(excelDTO.getUncompletedReason());
            // 设置用户ID，实现数据隔离
            record.setUserId(userId);
            
            // 业务逻辑校验：当应达到框数大于实际框数时，未完成原因必须填写
            if (record.getTargetBoxCount() != null && record.getActualBoxCount() != null &&
                record.getTargetBoxCount() > record.getActualBoxCount() && 
                (record.getUncompletedReason() == null || record.getUncompletedReason().trim().isEmpty())) {
                log.warn("数据校验失败：当应达到框数大于实际框数时，必须填写未完成原因");
                // 在实际应用中，你可能需要更复杂的处理逻辑，比如跳过这条数据或记录错误日志
                continue;
            }
            
            labelerDailyOutputService.save(record);
        }
        log.info("存储数据库成功！");
    }
}